package com.cms.sync.manager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cms.sync.model.ImportChannelSyncData;
import com.cms.sync.model.ImportCpSyncData;
import com.cms.sync.model.ImportSyncData;
import com.cms.sync.model.XiaomiSyncLog;
import com.cms.sync.service.DefaultSyncLogService;
import com.cms.sync.service.SyncImportDataService;
import com.cms.sync.service.SyncImportDataServiceImpl;
import com.cms.sync.service.XiaomiSyncLogServiceImpl;
import com.danga.MemCached.MemCachedClient;
import com.util.MemCachedUtil;
import com.util.Singleton;
import com.util.Util;
import com.utils.queue.DefaultQueue;
import com.utils.string.EncodingUtils;
import com.utils.string.EncodingUtils.CHARSET;

public class XiaomiSyncLogManager extends Singleton {

	public static void main(String[] args) {
		/*Thread t1 = new Thread(){
			public void run(){
				XiaomiSyncLogManager m = XiaomiSyncLogManager.getInstance();
				int i=0;
				try {
					while(i<100){
						XiaomiSyncLog t = new XiaomiSyncLog();
						t.setAppid(i+"_Thread1");
						m.saveXiaomiSyncLog(t);
						i++;
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		};
		t1.start();*/
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, -2);
		Date d = Util.stringToDate("2014-06-16", "yyyy-MM-dd");
		System.out.println(Util.dateToString(c.getTime(),"yyyy-MM-dd"));
		System.out.println(c.getTime().after(d));
	}
	
	public static XiaomiSyncLogManager getInstance()
	{
		return (XiaomiSyncLogManager) XiaomiSyncLogManager.getInstance(XiaomiSyncLogManager.class.getName());
	}
	
	public XiaomiSyncLogManager(){
		queue = new DefaultQueue(100);
		relevanceAndpointCode=new HashMap<String,String>();
		service = new XiaomiSyncLogServiceImpl();
		syncservice=new SyncImportDataServiceImpl();
		List<XiaomiSyncLog> itemlist = service.getAll();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, -2); //将时间设置为当前时间的前3天(包含今天)
		for (XiaomiSyncLog item : itemlist) {
			String tmpKey = item.getAppid()+"_"+item.getProductcode();
			if(!relevanceAndpointCode.containsKey(tmpKey)){
				//将对应信息添加到缓存
				relevanceAndpointCode.put(tmpKey, syncservice.getMessageByrelevanceIdAndpointCode(item.getAppid(), item.getProductcode()));
			}
			String tmpStr = relevanceAndpointCode.get(tmpKey);
			if(tmpStr!=null&&tmpStr.length()>0){
				String[] arr = tmpStr.split(",");
				//yyyyMMddHHmm_appnumber_cpid_goodsid_channelid
				String tmpdate = Util.dateToString(Util.stringToDate(item.getPaytime(), "yyyy-MM-dd HH:mm:ss"), "yyyyMMddHHmm");
				String tkey = "xiaomi_"+tmpdate+"_"+arr[0]+"_"+arr[1]+"_"+arr[2]+"_"+channelid;
				if(!allUid.keyExists(tkey)){
					allUid.add(tkey, new ArrayList<String>());
				}
				ArrayList<String> al = (ArrayList<String>)allUid.get(tkey);
				al.add(item.getUid());
				allUid.replace(tkey, al);

				//保存近3天的数据
				Date d = Util.stringToDate(item.getPaytime().split(" ")[0], "yyyy-MM-dd");			
				if(d.after(c.getTime())){
					tkey=tkey+"_active";
					if(!allUid.keyExists(tkey)){
						allUid.add(tkey, new ArrayList<String>(),60*60*24*3);
					}
					ArrayList<String> al1 = (ArrayList<String>)allUid.get(tkey);
					al1.add(item.getUid());
					allUid.replace(tkey, al1);
				}
			}
		}
		new SyncThread().start();
	}
	
	private Map<String,String> relevanceAndpointCode=null;
	private DefaultSyncLogService<XiaomiSyncLog> service;
	private SyncImportDataService syncservice;
	
	private MemCachedUtil allUid = MemCachedUtil.getInstance();
	
	private DefaultQueue queue;
	private int wait = 0;
	
	private final int channelid=100022; //小米SDK 初始化
	private final String operator="未知";
	private final String source="小米SDK同步";
	private final String province="未知";
	
	public boolean saveXiaomiSyncLog(XiaomiSyncLog t){
		if(queue.isFull()){
			queue.setMaxSize(queue.getMaxSize()+50);
		}
		push(t);

		return service.save(t);
	}
	
	public void push(Object obj) {
		synchronized (queue) {
			queue.push(obj);
			if (wait > 0) {
				queue.notify();
			}
		}
	}
	
	public Object pop() {
		synchronized (queue) {
			if (queue.isEmpty()) {
				wait++;
				try {
					queue.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				wait--;
			}
			return queue.pop();
		}
	}
	
	
	class SyncThread extends Thread{

		@Override
		public void run() {
			try {
				while(true){
					XiaomiSyncLog t = (XiaomiSyncLog) pop();
					boolean flag = saveSyncImportData(t);
					if(!flag){
						queue.push(t);
					}
					
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 小米平台同步添加
	 * @param t
	 * @return
	 */
	private boolean saveSyncImportData(XiaomiSyncLog t){
		boolean flag=true;
		
		int newUser=0; //新增用户数
		int activeUser=0; //活跃用户数
		int payUser=0; //付费用户数
		int payNumber=1; //付费次数
		float fee=0;
		
		ImportSyncData importData = new ImportSyncData();
		importData.setPaidnumber(payNumber);
		importData.setChannelid(channelid);
		importData.setOperator(operator);
		importData.setProvince(province);
		importData.setSource(source);
		
		try {
			//时间
			Date d = Util.stringToDate(t.getPaytime(), "yyyy-MM-dd HH:mm:ss");
			Calendar c = Calendar.getInstance();
			c.setTime(d);
			String day = Util.dateToString(c.getTime(), "yyyyMMdd");
			int hour= c.get(Calendar.HOUR_OF_DAY);
			int minute=c.get(Calendar.MINUTE);
			importData.setDay(Integer.valueOf(day));
			importData.setHour(hour);
			importData.setMinute(minute);
			
			String uid = t.getUid();
			String tmpKey = t.getAppid()+"_"+t.getProductcode();
			if(!relevanceAndpointCode.containsKey(tmpKey)){
				//将对应信息添加到缓存
				relevanceAndpointCode.put(tmpKey, syncservice.getMessageByrelevanceIdAndpointCode(t.getAppid(), t.getProductcode()));
			}
			//get appnumber cpid goodsid goodsname
			String tmpStr = relevanceAndpointCode.get(tmpKey);
			if(tmpStr!=null&&tmpStr.length()>0){
				String[] arr = tmpStr.split(",");
				//yyyyMMddHHmm_appnumber_cpid_goodsid_channelid
				String tmpdate = Util.dateToString(Util.stringToDate(t.getPaytime(), "yyyy-MM-dd HH:mm:ss"), "yyyyMMddHHmm");
				String tkey = "xiaomi_"+tmpdate+"_"+arr[0]+"_"+arr[1]+"_"+arr[2]+"_"+channelid;
				if(!allUid.keyExists(tkey)){
					allUid.add(tkey, new ArrayList<String>());
				}
				ArrayList<String> al = (ArrayList<String>)allUid.get(tkey);
				//把uid加进全局缓存
				if(!al.contains(uid))
				{
					newUser++;
					al.add(uid);
					allUid.replace(tkey, al);
				}
				
				//活跃用户
				tkey=tkey+"_active";
				if(!allUid.keyExists(tkey)){
					allUid.add(tkey, new ArrayList<String>(),60*60*24*3);
				}
				ArrayList<String> al1 = (ArrayList<String>)allUid.get(tkey);
				if(!al1.contains(uid)){
					activeUser++;
					al1.add(uid);
					allUid.replace(tkey, al1);
				}
				
				//set appnumber cpid goodsid goodsname
				importData.setAppnumber(arr[0]); 
				importData.setCpid(Integer.parseInt(arr[1]));
				importData.setGoodsid(Integer.parseInt(arr[2]));
				importData.setGoodsname(EncodingUtils.encode(arr[3], CHARSET.ISO88591, CHARSET.UTF8));
			}
			importData.setNewusers(newUser);
			importData.setActiveuser(activeUser);
			//付费用户  订单状态，TRADE_SUCCESS 代表成功
			if(t.getOrderstatus().equals("TRADE_SUCCESS")){
				payUser++;
				fee=t.getPayfee();
			}
			importData.setPayingcustomers(payUser);
			importData.setFee(fee);
			
			syncservice.saveImportSyncData(importData);
			syncservice.saveImportCpSyncData(new ImportCpSyncData(importData));
			syncservice.saveImportChannelSyncData(new ImportChannelSyncData(importData));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("出现问题，错误信息："+e.getMessage());
			flag=false;
		}
		return flag;
	}
	
	public boolean isRepeatOrder(String orderId){
		//处理重复订单
		return service.idRepeatOrder(orderId).size()>0;
	}
}
